import React, { useState } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Typography, Menu, Dropdown, Space, Button } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import asyncRoutes from '../../../router/asyncRoutes';
import DialogModalIcon from './DialogModalIcon';

interface Item {
  key?: string | React.ReactText;
  path?: string | undefined;
  icon?: string;
  address?: string;
  [prototype: string]: any;
}

let originData: Item[] = asyncRoutes;
for (let i = 0; i < originData.length; i++) {
  originData[i]['key'] = i.toString()
  let child: any = originData[i].children;
  if(child) {
    for (let j = 0; j < child.length; j++) {
      child[j]['key'] = i.toString() + j
    }
  }
}
interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: 'number' | 'text';
  record: Item;
  index: number;
  children: React.ReactNode;
}

const SystemMenu = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState('');
  const [dialogVisible, setDialogVisible] = useState<boolean>(false);
  // let recordItem: Item = {};

  const handleSetIcon = (icon: string|undefined) => {
    data.map((item: Item) => {
      if(item.key === editingKey) {
        item.icon = icon
      } else {}
      return item
    })
    setData(data)
    // setData([(item: any) => {
    //   console.log(item)
    //   // if(item.key === editingKey) {
    //   //   item.icon == icon
    //   // }
    // }])
    // setData((item: Item) => {
    //   if(item.key === editingKey) {
    //     item.icon == icon
    //   }
    // })
    // setEditingKey((key) => (data[editingKey].icon = icon))
    // record.icon = icon
    // data.map((item)=>{
    //   if(recordItem.key === item.key) {
    //     setEditingKey(item.key
    //   }
    // })
    setDialogVisible(false)
  }
  
  const editIcon = (event: any, record: Item) => {
    // console.log(record, 'record')
    // recordItem = record
    setDialogVisible(true)
  }

  const EditableCell: React.FC<EditableCellProps> = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;

    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            {dataIndex === 'icon' ? <Button type="text" onClick={(event) => editIcon(event, record)}>{record.icon || '无'}</Button> : inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  const isEditing = (record: Item) => record.key === editingKey;

  // const edit = (record: Partial<Item> & { key: React.Key }) => {
  //   form.setFieldsValue({ name: '', age: '', address: '', ...record });
  //   setEditingKey(record.key);
  // };

  const edit = (record: any) => {
    form.setFieldsValue({ ...record });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };
// : React.Key
  const save = async (key: any) => {
    try {
      const row = (await form.validateFields()) as Item;

      const newData = [...data];
      const index = newData.findIndex(item => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      editable: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: '路由地址',
      dataIndex: 'path',
      editable: true,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      editable: true,
      align: 'center' as const
    },
    {
      title: '序号',
      dataIndex: 'sort',
      editable: true,
    },
    {
      title: '权限标识',
      dataIndex: 'permission',
      editable: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '180px',
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        const menu = (
          <Menu>
            <Menu.Item>同级菜单</Menu.Item>
            <Menu.Item>子菜单</Menu.Item>
          </Menu>
        );
        return (
          <Space>{
            editable ? (
            <span>
              <span onClick={() => save(record.key)} style={{ marginRight: 8 }}>
                保存
              </span>
              <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
                <span>取消</span>
              </Popconfirm>
            </span>
          ) : (
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
              编辑
            </Typography.Link>
          )
        }
          <Dropdown overlay={menu}>
            <span className="ant-dropdown-link">
            添加菜单 <DownOutlined />
            </span>
          </Dropdown>
          </Space>
        )
      },
    },
  ];

  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        // inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        align: col.align || '',
        editing: isEditing(record),
      }),
    };
  });

  return (
    <>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
      {
        dialogVisible && <DialogModalIcon dialogVisible={dialogVisible} handleSetIcon={handleSetIcon} />
      }
    </>
  );
};

export default SystemMenu;
